﻿using System;
using System.Collections.Generic;

namespace CGF
{

    [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
    public class CGFAttribute : Attribute { }

    public class AttributeClass
    {
        public Type classType;
        public object attributeObject;
        public AttributeClass(Type classType, object attributeObject)
        {
            this.classType = classType;
            this.attributeObject = attributeObject;
        }
    }

    public static class AttributeHelper
    {

        private static Dictionary<string, List<AttributeClass>> allAttributeClass = new Dictionary<string, List<AttributeClass>>();

        public static void Init()
        {
            Type[] types = CGFramework.Instance.assembly.GetTypes();
            List<Type> allAttributes = GetAllAttributes(types);
            foreach (Type attribute in allAttributes)
            {
                List<AttributeClass> objs = new List<AttributeClass>();
                foreach (var type in types)
                {
                    try
                    {
                        var attrs = type.GetCustomAttributes(attribute, false);
                        if (attrs.Length > 0)
                        {
                            objs.Add(new AttributeClass(type, attrs[0]));
                        }
                    }
                    catch { }
                }
                if (objs.Count > 0)
                {
                    allAttributeClass.Add(attribute.Name, objs);
                }
            }
        }

        /// <summary>
        /// 获取所有被传入的特性类型标注的类
        /// </summary>
        public static List<AttributeClass> GetTypes(Type attributeTypes)
        {
            if (allAttributeClass.ContainsKey(attributeTypes.Name))
            {
                return allAttributeClass[attributeTypes.Name];
            }
            return null;
        }

        private static List<Type> GetAllAttributes(Type[] allClass)
        {
            List<Type> list = new List<Type>();
            for (int i = 0; i < allClass.Length; i++)
            {
                Type type = allClass[i];
                if (type.IsAbstract) continue;
                if (type.IsSubclassOf(typeof(CGFAttribute)))
                {
                    list.Add(type);
                }
            }
            return list;
        }
    }
}
